import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../function/model/single_chat_model.dart';
import '../../function/model/single_chat_message_model.dart';
import '../../function/model/user_model.dart';
import '../../function/state/single_chat_state.dart';
import '../../function/state/single_chat_message_state.dart';
import '../../function/state/user_state.dart';
import '../../function/widgets/login_dialog_widget.dart';
import '../../function/widgets/report_dialog.dart';

/// 单聊聊天页面控制器
class SingleChatController extends GetxController {
  final SingleChatState _singleChatState = Get.find<SingleChatState>();
  final SingleChatMessageState _singleChatMessageState =
      Get.find<SingleChatMessageState>();
  final UserState _userState = Get.find<UserState>();

  final TextEditingController _messageController = TextEditingController();
  final FocusNode _messageFocusNode = FocusNode();

  // 当前单聊
  final Rx<SingleChatModel?> _currentChat = Rx<SingleChatModel?>(null);

  // 是否正在发送消息
  final RxBool _isSending = false.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeController();
  }

  @override
  void onClose() {
    _messageController.dispose();
    _messageFocusNode.dispose();
    super.onClose();
  }

  /// 初始化控制器
  void _initializeController() {
    final arguments = Get.arguments;
    if (arguments is SingleChatModel) {
      _currentChat.value = arguments;
      _setupChatEnvironment();
    }
  }

  /// 设置聊天环境
  void _setupChatEnvironment() {
    if (_currentChat.value == null) return;

    // 设置当前用户ID
    if (_userState.isLoggedIn && _userState.currentUser != null) {
      final userId = _userState.currentUser!.id;
      _singleChatState.setCurrentUserId(userId);
      _singleChatMessageState.setCurrentUserId(userId);
    }

    // 进页面即标记对方消息为已读
    _singleChatMessageState.markChatMessagesAsRead(_currentChat.value!.id);
  }

  /// 获取当前单聊
  SingleChatModel? get currentChat => _currentChat.value;

  /// 获取消息控制器
  TextEditingController get messageController => _messageController;

  /// 获取焦点节点
  FocusNode get messageFocusNode => _messageFocusNode;

  /// 是否正在发送消息
  bool get isSending => _isSending.value;

  /// 获取当前单聊的消息
  List<SingleChatMessageModel> getCurrentChatMessages() {
    if (_currentChat.value == null) return [];
    return _singleChatMessageState.getMessagesByChatId(_currentChat.value!.id);
  }

  /// 检查是否为当前用户
  bool isCurrentUser(String senderId) {
    if (!_userState.isLoggedIn || _userState.currentUser == null) {
      return false;
    }
    return senderId == _userState.currentUser!.id;
  }

  /// 根据ID获取用户
  UserModel? getUserById(String userId) {
    return _userState.getUserById(userId);
  }

  /// 获取当前用户头像
  String getCurrentUserAvatar() {
    if (!_userState.isLoggedIn || _userState.currentUser == null) {
      return 'assets/images/avatar1.png';
    }
    return _userState.currentUser!.avatar;
  }

  /// 获取对端用户
  UserModel? getOtherUser() {
    if (_currentChat.value == null) return null;
    final otherId = _currentChat.value!.getOtherUserId(
      _singleChatState.currentUserId,
    );
    if (otherId == null || otherId.isEmpty) return null;
    return _userState.getUserById(otherId);
  }

  /// 发送消息
  void sendMessage() {
    final content = _messageController.text.trim();
    if (content.isEmpty || _currentChat.value == null) return;

    // 检查用户是否已登录
    if (!_userState.isLoggedIn) {
      Get.dialog(const LoginDialogWidget(), barrierDismissible: true);
      return;
    }

    // 发送消息
    _isSending.value = true;
    final sent = _singleChatMessageState.sendTextMessage(
      chatId: _currentChat.value!.id,
      content: content,
    );
    _singleChatState.updateChatLastMessage(
      chatId: _currentChat.value!.id,
      content: sent.content,
      senderId: sent.senderId,
      sendTime: sent.sendTime,
    );
    _messageController.clear();
    _isSending.value = false;
  }

  /// 举报当前对话：弹出举报弹窗，提交后清空该对话消息并返回
  void reportCurrentChat() {
    if (_currentChat.value == null) return;
    ReportDialogUtils.showReportDialog(
      onReportSubmitted: (String reportType) {
        Get.back();
      },
    );
  }
}
